package com.geekaca.web.servlet;

import com.geekaca.web.mapper.UserMapper;
import com.geekaca.web.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private static SqlSession openSession() {
        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream ips = null;
        try {
            ips = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);
        //2. 获取SqlSession 对象, 用农来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF8");
        resp.setHeader("Content-type", "text/html; charset=utf-8");
//        resp.setContentType("text/html;charset=utf-8");

        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        System.out.println("收到参数: " + uname);

        //显示在网页上
        PrintWriter writer = resp.getWriter();
        // 调用mybatis
        SqlSession sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername(uname);
        user.setPassword(pwd);
        int cnt = userMapper.selectByUnamePass(user);
        if (cnt > 0) {
//            writer.write("登录成功 ！  欢迎您： " + uname);

            req.getRequestDispatcher("/main").forward(req, resp);
        } else {
            writer.write("登录失败！");
        }


    }
}
